
    <template>
    <el-card shadow="never" class="index">
        <template #header>
            <div class="card_header">
                <b>学生管理</b>
            </div>
        </template>

        <el-card class="box-card" shadow="never">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="学生名">
                    <el-input v-model="formInline.name" placeholder="学生名"></el-input>
                </el-form-item>
                <el-form-item label="班级">
                    <el-input v-model="formInline.cls" placeholder="班级"></el-input>
                </el-form-item>
                <el-form-item label="政治面貌">
                    <el-input v-model="formInline.politics" placeholder="政治面貌"></el-input>
                </el-form-item>
                <!-- <el-form-item label="Activity zone">
                    <el-select v-model="formInline.region" placeholder="Activity zone">
                        <el-option label="Zone one" value="shanghai"></el-option>
                        <el-option label="Zone two" value="beijing"></el-option>
                    </el-select>
                </el-form-item>-->
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-table stripe style="width: 100%" v-loading="loading" :ref="multipleTableRef" :data="filterTableData"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" sortable label="序号" width="60" />
            <el-table-column label="头像" width="60" prop="address">
                <template #default="scope">
                    <el-image :src="'http://localhost:5199' + scope.row.avatar_url" fit="fill">
                        <template #error>
                            <div class="image-slot">
                                <el-icon>
                                    <icon-picture />
                                </el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="名称" sortable prop="name">
                <template #default="scope">
                    <el-popover effect="light" trigger="hover" placement="top" width="auto">
                        <template #default>
                            <div>编号: {{ scope.row.username }}</div>
                        </template>
                        <template #reference>
                            <p>
                                <el-tag>{{ scope.row.name }}</el-tag>
                            </p>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="培养人1" prop="tname">
            </el-table-column>
            <el-table-column label="培养人2" prop="t2name">
            </el-table-column>
            <el-table-column label="班级" prop="cls" />
            <el-table-column label="手机" sortable prop="phone" />
            <el-table-column label="政治面貌" prop="politics" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
            <el-pagination background hide-on-single-page :current-page="pageNum" :page-size="pageSize"
                :total="totalNum" @current-change="handlePageChange" layout="prev, pager, next"
                style="margin-bottom:10px;"></el-pagination>
            <el-button type="danger" @click="handleSelectDelete">删除</el-button>
            <el-button type="primary" @click="handleAdd">添加</el-button>
        </div>
    </el-card>
</template>

<script>
import { getCurrentInstance, onBeforeMount, reactive, ref, toRaw, computed } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons'
import { studentService, teacherService, approveService } from '../../interfaces/service'
import { useRouter } from 'vue-router';


export default {
    components: { ElTable, IconPicture },
    setup() {
        const { proxy } = getCurrentInstance()
        const router = useRouter()

        onBeforeMount(() => {
            loadTalbeData();
            loadSelectTeachers();
        })

        const loadSelectTeachers = () => {
            teacherService.getSelTeachers().then(res => {
                if (res.success) {
                    let list = res.data
                    teachers.value = list;
                }
            });
        }

        const loadTalbeData = () => {
            let data = {
                "pageSize": pageSize.value,
                "pageNum": pageNum.value,
            };
            var formSearchCondition = toRaw(formInline);
            Object.keys(formSearchCondition).forEach(key => {
                if (formSearchCondition[key]) {
                    data[`conditions[${key}]`] = formSearchCondition[key]
                }
            });
            loading.value = true
            studentService.getStudents(data)
                .then(res => {
                    loading.value = false
                    if (res.success) {
                        let list = res.data.list
                        let total_num = res.data.totalNum
                        totalNum.value = total_num
                        tableData.value = list
                    }
                })
        }

        const handleSelectTeacher = (id, row, isFirst) => {
            // 查找老师的id号
            const val = teachers.value.find(item => item.id === id) || "无";
            // post发送的数据
            const stuId = row.id;
            const order = isFirst ? 1 : 2;
            const teaId = id;
            // 确认修改
            ElMessageBox.confirm('确认修改?', '提示', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                callback: (action) => {
                    if (action === 'confirm') {
                        const post_data = { stuId, teaId, order }
                        approveService.assignment(post_data).then(res => {
                            if (res.success) {
                                // 修改成功就改变选择
                                if (isFirst) {
                                    row.tid = val.id;
                                    row.tname = val.name;
                                } // 第一个培养人
                                else {
                                    row.t2id = val.id;
                                    row.t2name = val.name;
                                } // 第二个培养人
                                ElMessage.success("切换成功");
                            } else {
                                // ElMessage.warning("切换失败, " + res.message);
                                console.warn(res.message);
                            }
                        });
                    }
                    else if (action === 'cancel') {
                        console.log({ id, row })
                    }
                },
            })

        }
        const teachers = ref([])

        const delConfig = [
            "确定删除?",
            "提示",
            {
                confirmButtonText: '删除',
                confirmButtonClass: "del-confirm-button",
                cancelButtonText: '取消',
                type: 'error',
                draggable: true
            }
        ]

        // do not use same name with ref
        const formInline = reactive({
            name: '',
            phone: '',
            email: '',
        })

        // 处理搜索按钮
        const handleSearch = () => {
            loadTalbeData()
        }

        // 多选删除
        const handleSelectDelete = (raw) => {

            if (multipleSelection.value && multipleSelection.value.length > 0) {
                ElMessageBox.confirm(...delConfig).then(() => {
                    let ids = '';
                    multipleSelection.value.forEach(item => {
                        ids += item.id + ','
                    });
                    studentService.delStudents({ id: ids })
                        .then(res => {
                            if (res.success) {
                                ElMessage.success("删除成功")
                                loadTalbeData()
                            }
                        })
                })
            } else {
                ElMessage.info("请先选中一行数据")
            }
        }

        // 添加学生
        const handleAdd = () => {
            router.replace('/student/add')
        }


        const loading = ref(false)
        //表格引用
        const multipleTableRef = ref(null)
        // 表格选中的数据
        const multipleSelection = ref(null)

        // 表格改变事件
        const handleSelectionChange = (val) => {
            // 表格选中的数据
            multipleSelection.value = val
        }

        // 过滤标签
        const filterTag = (value, row) => {
            return row.tag === value
        }

        // 表格数据
        const tableData = ref([])

        // NOTE: 本地过滤, 这里没用到
        const search = ref('')
        const filterTableData = computed(() =>
            // NOTE: 写一些过滤方法
            tableData.value.filter(
                (data) =>
                    !search.value || data.name.toLowerCase().includes(search.value.toLowerCase())
            )
        )

        // 编辑
        const handleEdit = (index, row) => {
            router.push({ name: 'UpdateStudentForTeacher', params: { id: row.id } })
        }

        // 删除
        const handleDelete = (index, row) => {
            if (index >= 0) {
                ElMessageBox.confirm(...delConfig).then(() => {
                    studentService.delStudents({ id: row.id })
                        .then(res => {
                            if (res.success) {
                                filterTableData.value.splice(index, 1)
                                ElMessage.success("删除成功")
                            }
                        })
                })
            }
        }

        // 分页组件
        const pageNum = ref(1)
        const pageSize = ref(10)
        const totalNum = ref(10)
        // 当前页改变事件
        const handlePageChange = (n) => {
            pageNum.value = n
            loadTalbeData()
        }

        return {
            formInline,
            loading,
            multipleSelection,
            multipleTableRef,
            pageNum,
            pageSize,
            totalNum,
            filterTableData,
            teachers,
            handleSearch,
            filterTag,
            handleEdit,
            handleAdd,
            handleDelete,
            handleSelectDelete,
            handleSelectionChange,
            handlePageChange,
            handleSelectTeacher,
        }
    }
}
</script>

<style lang="scss" scoped>
.card_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.box-card {
    margin-bottom: 50px;
}

.del-confirm-button {
    background-color: red;
}
</style>

